package cn.jbooter.ctx.autoconfigure.startup;

import java.util.List;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.OrderComparator;
import org.springframework.web.context.ServletContextAware;

import cn.jbooter.ctx.autoconfigure.startup.intf.WebApplicationStartupInitializer;

/**
 * spring上下文context初始化完毕后监听器
 * @author HeJian
 *
 */
public class WebApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> ,ServletContextAware{
	private final Logger logger = LoggerFactory.getLogger(WebApplicationContextListener.class);
	
	private ServletContext servletContext;
	
	@Autowired(required=false)
	private List<WebApplicationStartupInitializer> webInitializerList;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		ApplicationContext ctx = event.getApplicationContext();
		if(ctx.getParent() == null){
			logger.info(">>>>>> root container : "+ctx.getDisplayName());
			if(webInitializerList!=null && webInitializerList.size()>0) {
				logger.info(">>>>>> Initializing custome web component ......");
				OrderComparator.sort(webInitializerList);
				for(WebApplicationStartupInitializer initializer: webInitializerList) {
					initializer.initialize(ctx, this.servletContext);
				}
			}
		}
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

}
